import React from 'react'
import { Upload, Icon, Modal, message } from 'antd';
import {connect} from "dva";
import { baseServerUrl } from '../../utils/Constant';
import { getAuthority } from '../../utils/authority';


function beforeUpload(file) {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('只支持 JPG/PNG 文件!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('超出 2MB!');
  }
  return isJpgOrPng && isLt2M;
}

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

@connect(({ fileUp, }) => ({
  assets: fileUp.assets,
}))
class PicturesWall extends React.Component {

  state = {
    fileList: [],
    previewVisible: false,
    previewImage: '',
  };

  componentDidMount() {
    const {  assets, type } = this.props;
    let fileList = []
    if(type === 'assets'){
      fileList = assets
    }
    this.setState({
      fileList: fileList
    })
  }

  handleCancel = () => this.setState({ previewVisible: false });

  handlePreview = async file => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }

    this.setState({
      previewImage: file.url || file.preview,
      previewVisible: true,
    });
  };

  handleChange = ({ fileList }) => {
    this.setState({
      fileList
    })
    const { type, dispatch } = this.props
    if(type === 'assets'){
      dispatch({
        type: 'fileUp/assetsChange',
        payload: fileList
      })
    }
  }

  render() {
    const { previewVisible, previewImage, fileList } = this.state;
    const { fileSize } = this.props
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div>Upload</div>
      </div>
    );
    return (
      <div>
        <Upload
          action={`${baseServerUrl}/oss/uploadImg`}
          headers={{token: getAuthority()}}
          withCredentials={true}
          listType="picture-card"
          fileList={fileList}
          onPreview={this.handlePreview}
          onChange={this.handleChange}
          beforeUpload={beforeUpload}
        >
          {fileList.length >= fileSize ? null : uploadButton}
        </Upload>
        <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
          <img alt="example" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </div>
    );
  }
}
export default PicturesWall;
